package com.ruoyi.framework.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpTools;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("ryTask")
public class RyTask
{

    protected final Logger log = LoggerFactory.getLogger(BaseController.class);
    public static String BASE_API="https://carrier.wbtech.com";

    public Map<Long,Tiaojian> tjMap=new HashMap<>();//存放条件
    public List<CustUser> mainlist=new ArrayList<>();//
    public List<CustUser> zzhList=new ArrayList<>();//


    String date=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    long sdate=System.currentTimeMillis();
    long edate=System.currentTimeMillis();

    @Autowired
    RedisCache redisCache;

    @Autowired
    ICustUserService custUserService;
    @Autowired
    ISysUserService userService;

    @Autowired
    ITiaojianService tiaojianService;
    @Autowired
    IDanService danService;
    @Autowired
    IOrderService orderService;


    int index=0;


    public RyTask(){
        initDate();
    }


    /**
     * 入口
     */
    public void ryNoParams()
    {

        if(zzhList.size()<3){
            log.error("子账户不足3个,将无法正常运行");
            return;
        }

        if(index>=zzhList.size()){
            index=0;
        }


        getList(zzhList.get(index).getUserName());
        index++;


    }

    /**
     * 入口
     */
    public void refreshMain()
    {
        initDate();
        if(null==mainlist){
            return;
        }
        for(CustUser custUser:mainlist){
            getList(custUser.getUserName());
        }
    }


    public  void getList(String username){

        String token=redisCache.getCacheObject("username:token:"+username);



        Map<String,String> map=new HashMap<>();
        map.put("parentCatalogId","1");

        map.put("rqStart",sdate+"");
        map.put("rqEnd",edate+"");

        map.put("operateType","1");
        map.put("quoteType","0");
        map.put("page","0");
        map.put("sizePerPage", 30+"");

        String response= HttpTools.post(BASE_API+"/api/pro/business/publish/carrier/carrierPublishList", JSON.toJSONString(map),token);


        JSONObject jo=null;
        try{
            jo=JSON.parseObject(response);
        } catch (Exception e){
            log.error("登录失败:"+response);
            return;
        }


        if(jo.getInteger("code")==2){
            login(username);
            log.error(username+" 重新登录一次:"+jo.getString("message"));
            return;
        }if(jo.getInteger("code")==1){
            log.error("操作频繁了,自动停止请求");
            return;
        }else if(jo.getInteger("code")!=0){
            log.error("查询失败:"+jo.getString("message"));
            return;
        }


        JSONObject data=jo.getJSONObject("data");
        int total=data.getInteger("totalElements");

        //log.info("扫描中,本次扫描到订单数量:"+total);

        log.info("用户"+username+"  根据条件查询到"+total+"条订单 正在筛选推荐订单 ");


        if(total<=0){
            log.error("暂无数据:");
            return;
        }

        List<Dan> danList=JSON.parseArray(data.getString("content"),Dan.class);
        Dan dan=null;
        if(null==danList||danList.size()<=0){
            log.info("本次查询为空");return;
        }
        log.info("本次查询数量为:"+danList.size()+"条,开始提交订单");

        String publishId;
        for(int i=0;i<danList.size();i++){
            dan=danList.get(i);
            redisCache.setCacheObject("publishId:"+dan.getPublishId(),dan.getPublishId(),2,TimeUnit.DAYS);
            //匹配条件

            if(null!=redisCache.getCacheObject("doSubmit:publishId:"+dan.getPublishId())){
                //log.info("货源编号"+dan.getPublishId()+" 已经提交过了");
                continue;
            }

            doSubmit(dan.getPublishId(),getUserName(dan));// 找到符合条件的 用户提交订单

        }
    }


    /**
     * 提交抢单
     * @param publishId  订单编号
     */
    public  void doSubmit(String publishId,CustUser custUser) {
        if(null==custUser){
            return;
        }

        SysUser user=redisCache.getCacheObject("myhuanchunuser:"+custUser.getUserId());



        log.info("找到符合条件的订单:"+publishId);

        String token=redisCache.getCacheObject("username:token:"+custUser.getUserName());


        Map<String, Object> map = new HashMap<>();
        map.put("publishId",publishId);
        map.put("operateType", "web");
        map.put("ifZntsFlag", 0);


        String response=null;
        response = HttpTools.post(BASE_API + "/api/pro/business/publish/carrier/grabBill", JSON.toJSONString(map),token);


        Order order=new Order();
        order.setUserId(custUser.getUserId());
        order.setCustId(custUser.getId());
        order.setPublishId(publishId);

        JSONObject jo =null;
        // new JSONObject();
        //jo.put("code",0);// 模拟抢单成功

        try {
            jo = JSON.parseObject(response);
        } catch (Exception e) {
            log.error("抢单失败:" + response);
            return;
        }

        if(jo.getInteger("code")==2){
            order.setState("0");
            orderService.insertOrder(order);

            login(custUser.getUserName());
            log.error(" 重新登录一次:"+jo.getString("message"));
            return;
        }

        if (jo.getInteger("code") != 0) {
            order.setState("0");
            orderService.insertOrder(order);

            log.error("抢单失败:" + jo.getString("message"));
            return;
        }

        redisCache.setCacheObject("doSubmit:publishId:"+publishId,publishId,2,TimeUnit.DAYS);

        if(user!=null){
            user.setBalance(user.getBalance().subtract(user.getNum()));
            redisCache.setCacheObject("myhuanchunuser:"+custUser.getUserId(),user);
            userService.updateUser(user);
        }


        order.setState("1");
        orderService.insertOrder(order);


        log.info("抢单成功:"+response);

    }




    public  CustUser getUserName(Dan dan){

        /**
         * 竞价排名  优先排队
         */
        sort();

        for (CustUser custUser:mainlist){

            Tiaojian tiaojian=tjMap.get(custUser.getUserId());
            if(null==tiaojian){
                return custUser;
            }

            //货物品种
            //0=全部
            //1=钢铁
            //2=矿石
            //3=焦炭
            //4=煤炭
            //5=化肥

            boolean fa=click(tiaojian.getAppointTeamType(),dan.getAppointTeamType(),false);
            if(!fa){
                continue;
            }

            fa=click(tiaojian.getParentCatalogId(),dan.getCatalogId(),false);
            if(!fa){
                continue;
            }

            //条件匹配 业务类型 1=计划模式 2=单车模式
            fa=click(tiaojian.getCarrierCarryMode(),dan.getCarrierCarryMode(),false);
            if(!fa){
                continue;
            }

            //条件匹配 取单地
            fa=click2(tiaojian.getBillPlate(),dan.getBillPlate(),true);
            if(!fa){
                continue;
            }

            //条件匹配 装货地
            fa=click2(tiaojian.getStartPlate(),dan.getStartPlate(),true);
            if(!fa){
                continue;
            }


            //条件匹配 目的地
            fa=click2(tiaojian.getEndPlate(),dan.getEndPlate(),true);
            if(!fa){
                continue;
            }

            //条件匹配 委托人
            fa=click(tiaojian.getClienter(),dan.getClienter(),false);
            if(!fa){
                continue;
            }

            //条件匹配 是否预付 0=否 1=是
            fa=click(tiaojian.getPrepayFlag(),dan.getPrepayFlag(),false);
            if(!fa){
                continue;
            }

            log.error("账户:"+custUser.getUserName()+"  获得本次货源:"+dan.getPublishId());



            return custUser;
        }

        //log.error("本次暂未获取到抢单主账号: 货源ID:"+dan.getPublishId());

        return null;
    }

    /**
     * 排序
     */
    private  void sort(){
        if(null==mainlist||mainlist.size()<=1){
            return;
        }
        Collections.sort(mainlist, new Comparator<CustUser>(){
            @Override
            public int compare(CustUser o1, CustUser o2) {
                if(o1.getUser().getNum().doubleValue()<o2.getUser().getNum().doubleValue()){
                    return 1;
                }
                return -1;
            }
        });

    }



    /**
     * 登录
     */
    public  void login(String username){
        Map<String,String> map=new HashMap<>();

        Integer loginMax=redisCache.getCacheObject("username:loginMax:"+username);
        if(null!=loginMax){
            if(loginMax>3){
                log.error("登录失败超过三次,3天内将不再重新登录");
                return;
            }
        }


        String password=redisCache.getCacheObject("password:"+username);
        map.put("username", username);
        map.put("password", password);

        String response= HttpTools.post(BASE_API+"/api/login", JSON.toJSONString(map),null);

        JSONObject jo=null;
        try{
            jo=JSON.parseObject(response);
        } catch (Exception e){
            log.error("用户:"+username+" 登录失败 catch");
        }

        if(null==jo){
            log.error("用户:"+username+" 登录失败 jo is null");
            return;
        }

        //{"code":0,"message":null,"data":{"tk":"8b6addf1-b440-4203-9f7d-35d7b86111b3","ltk":null,"roles":["2"]}}
        if(jo.getInteger("code")!=0){
            loginMax=redisCache.getCacheObject("username:loginMax:"+username);
            if(null==loginMax){
                loginMax=0;
            }
            loginMax++;
            redisCache.setCacheObject("username:token:"+username,loginMax,3,TimeUnit.DAYS);

            log.error("用户:"+username+" 登录失败:"+jo.getString("message"));
            return;
        }

        String tk= jo.getJSONObject("data").getString("tk");
        redisCache.setCacheObject("username:token:"+username,tk,2,TimeUnit.DAYS);
        redisCache.setCacheObject("username:loginMax:"+username,0,3,TimeUnit.DAYS);


        log.info("用户:"+username+" 登录成功:");
    }




    /**
     * 同步账号
     */
    public  void synchroRedis(){
        tjMap.clear();
        mainlist.clear();
        zzhList.clear();

        List<Tiaojian> tjlist=tiaojianService.selectTiaojianList(new Tiaojian());
        if(null!=tjlist){
            for(Tiaojian t:tjlist){
                tjMap.put(t.getUserId(),t);
                redisCache.setCacheObject("myhuanchunuser:"+t.getUserId(),userService.selectUserById(t.getUserId()));
            }
        }

        List<CustUser> list=custUserService.selectCustUserList(new CustUser());
        if(null!=list){
            for(CustUser custUser:list){
                redisCache.setCacheObject("password:"+custUser.getUserName(),custUser.getPassword());
                if(custUser.getMain().equals("1")&&custUser.getUser().getBalance().doubleValue()>0){
                    mainlist.add(custUser);
                }else{
                    zzhList.add(custUser);
                }
            }
        }
    }

    /**
     * 初始化日期
     */
    public  void initDate()
    {
        try{
            date=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            sdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date+" 00:00:00").getTime();
            edate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date+" 23:59:59").getTime();
        }catch (Exception e){
            log.error("格式化日期错误:"+e.getMessage());
        }
    }


    /**
     * 检查条件
     * @param w  条件
     * @param v  内容
     * @param duoge 是否多个条件
     * @return
     */
    private  boolean click(String w,String v,boolean duoge){
        if(!duoge){
            if(StringUtils.isBlank(w)||StringUtils.isBlank(v)){
                return  true;
            }
            if(v.contains(w.trim())){
                return true;
            }else{
                return false;
            }
        }else{
            if(StringUtils.isBlank(w)||StringUtils.isBlank(v)){
                return  true;
            }

            String[] strs= w.split(";");
            if(null==strs||strs.length<=0){
                return true;
            }
            for (String a:strs){
                if(v.contains(a.trim())){
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * 检查条件
     * @param w  条件
     * @param v  内容
     * @param duoge 是否多个条件
     * @return
     */
    private  boolean click2(String w,String v,boolean duoge){
        if(!duoge){
            if(StringUtils.isBlank(w)||StringUtils.isBlank(v)){
                return  true;
            }
            if(!v.contains(w.trim())){
                return true;
            }else{
                return false;
            }
        }else{
            if(StringUtils.isBlank(w)||StringUtils.isBlank(v)){
                return  true;
            }

            String[] strs= w.split(";");
            if(null==strs||strs.length<=0){
                return true;
            }
            for (String a:strs){
                if(!v.contains(a.trim())){
                    return true;
                }
            }
            return false;
        }
    }




}
